import useMessage from "@/hooks/useMessage";
import { Form, Button, Input, FormInstance } from "antd";
import React, { useEffect, useRef, useState } from "react";
import TextArea from "antd/lib/input/TextArea";
import { addRoleApi, getRoleDetailApi, updateRoleApi } from "@/api/modules/user";
import { User } from "@/api/interface";

interface PropsType {
	type?: string;
	roleId?: number;
	onComfirm?: () => void;
}

const RoleAdd: React.FC<PropsType> = props => {
	const { type, onComfirm, roleId } = props;
	const { contextHolder, success } = useMessage();

	const [roleDetail, setRoleDetail] = useState<any>({});

	const getRoleDetail = async () => {
		const res = await getRoleDetailApi(roleId!);
		if (res.code === 200) {
			setRoleDetail(res.data);
		}
	};

	const formRef = useRef<FormInstance | null>(null);

	const onFinish = async (role: User.Role) => {
		if (type && roleId) {
			updateRoleApi({ ...role, id: roleId });
		} else {
			addRoleApi(role);
		}
		onComfirm && onComfirm();
		formRef.current?.setFieldsValue({
			name: ""
		});
		success("发布成功");
	};

	useEffect(() => {
		if (type) {
			getRoleDetail();
		}
	}, [roleId]);

	useEffect(() => {
		formRef.current?.resetFields();
		return () => {
			formRef.current?.setFieldsValue({
				name: ""
			});
		};
	}, [roleDetail]);

	return (
		<div>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={roleDetail}
			>
				<Form.Item label="角色" rules={[{ required: true }]} name="name">
					<Input />
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default RoleAdd;
